<template>
  <Dialog v-model="dialogVisible" title="更换分类">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="选择分类" prop="dirId">
        <el-tree-select
          v-model="formData.dirId"
          :data="dirList"
          :props="defaultProps"
          check-strictly
          node-key="id"
          placeholder="请选择上传分类"
        /> </el-form-item
    ></el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { FormRules } from 'element-plus'

defineOptions({ name: 'InfraFileForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const fileList = ref([]) // 文件列表
const formData = ref({
  dirId: ''
})
const formRules = reactive<FormRules>({
  dirId: [{ required: true, message: '请选择上传分组', trigger: 'change' }]
})
/** 获得目录树 */
import * as FileApi from '@/api/infra/file'
import { handleTree } from '@/utils/tree'
const defaultProps = {
  children: 'children',
  label: 'typeName',
  value: 'typeId',
  isLeaf: 'leaf',
  multiple: false,
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
}
const dirList = ref<Tree[]>([]) // 树形结构
const getTree = async () => {
  const res = await FileApi.getSimpleDirList()
  dirList.value = []
  dirList.value.push(...handleTree(res, 'typeId'))
}
/** 打开弹窗 */
const open = async (checkedFiles) => {
  dialogVisible.value = true
  resetForm()
  getTree()
  fileList.value = checkedFiles
  console.log(fileList.value)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitFileForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请选择文件')
    return
  }
  let ids = [] as any
  fileList.value.forEach((ele: any) => {
    ids.push(ele.id)
  })
  let param = {
    ids: ids,
    typeId: formData.value.dirId
  }
  await FileApi.fileExchange(param)
  message.success('更换成功')

  emit('success')
  dialogVisible.value = false
}

/** 文件上传成功处理 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
}
</script>
